package com.zzyl.nursing.service.impl;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.zzyl.common.exception.base.BaseException;
import com.zzyl.common.utils.DateUtils;
import com.zzyl.common.utils.uuid.UUID;
import com.zzyl.nursing.domain.*;
import com.zzyl.nursing.dto.CheckInApplyDto;
import com.zzyl.nursing.dto.CheckInElderDto;
import com.zzyl.nursing.mapper.*;
import com.zzyl.nursing.util.CodeGenerator;
import com.zzyl.nursing.vo.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.zzyl.nursing.service.ICheckInService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.transaction.annotation.Transactional;

import java.util.Arrays;

/**
 * 入住Service业务层处理
 *
 * @author ruoyi
 * @date 2025-05-27
 */
@Service
public class CheckInServiceImpl extends ServiceImpl<CheckInMapper, CheckIn> implements ICheckInService {
    @Autowired
    private CheckInMapper checkInMapper;
    @Autowired
    private ContractMapper contractMapper;

    /**
     * 查询入住
     *
     * @param id 入住主键
     * @return 入住
     */
    @Override
    public CheckIn selectCheckInById(Long id) {
        return getById(id);
    }

    /**
     * 查询入住列表
     *
     * @param checkIn 入住
     * @return 入住
     */
    @Override
    public List<CheckIn> selectCheckInList(CheckIn checkIn) {
        return checkInMapper.selectCheckInList(checkIn);
    }

    /**
     * 新增入住
     *
     * @param checkIn 入住
     * @return 结果
     */
    @Override
    public int insertCheckIn(CheckIn checkIn) {
        return save(checkIn) ? 1 : 0;
    }

    /**
     * 修改入住
     *
     * @param checkIn 入住
     * @return 结果
     */
    @Override
    public int updateCheckIn(CheckIn checkIn) {
        return updateById(checkIn) ? 1 : 0;
    }

    /**
     * 批量删除入住
     *
     * @param ids 需要删除的入住主键
     * @return 结果
     */
    @Override
    public int deleteCheckInByIds(Long[] ids) {
        return removeByIds(Arrays.asList(ids)) ? 1 : 0;
    }

    /**
     * 删除入住信息
     *
     * @param id 入住主键
     * @return 结果
     */
    @Override
    public int deleteCheckInById(Long id) {
        return removeById(id) ? 1 : 0;
    }

    @Autowired
    private ElderMapper elderMapper;

    @Autowired
    private BedMapper bedMapper;

    @Autowired
    private CheckInConfigMapper checkInConfigMapper;

    @Transactional
    @Override
    public void apply(CheckInApplyDto checkInApplyDto) {
        // 判断老人是否入住
        // 通过身份证号查询老人
        LambdaQueryWrapper<Elder> elderQueryWrapper = new LambdaQueryWrapper<>();
        elderQueryWrapper.eq(Elder::getIdCardNo, checkInApplyDto.getCheckInElderDto().getIdCardNo()).eq(Elder::getStatus, 1);
        Elder elder = elderMapper.selectOne(elderQueryWrapper);

        if (ObjectUtils.isNotEmpty(elder)) {
            throw new BaseException("老人已入住，请勿重复申请");
        }

        // 更新床位已入住
        Bed bed = new Bed();
        bed.setId(checkInApplyDto.getCheckInConfigDto().getBedId());
        bed.setBedStatus(1);
        bed.setRoomId(checkInApplyDto.getCheckInConfigDto().getRoomId()); // 级联设置 门牌与床位保持一致
        bedMapper.updateById(bed);

        // 更新或新增老人信息
        Elder newElder = insertOrUpdate(checkInApplyDto);

        // 新增合同办理
        Contract contract = new Contract();
        BeanUtil.copyProperties(checkInApplyDto.getCheckInContractDto(), contract);
        contract.setStatus(0);
        contract.setContractNumber(CodeGenerator.generateContractNumber());
        contract.setStartDate(checkInApplyDto.getCheckInConfigDto().getStartDate());
        contract.setEndDate(checkInApplyDto.getCheckInConfigDto().getEndDate());
        contract.setElderId(newElder.getId());
        contract.setElderName(newElder.getName());
        contractMapper.insertContract(contract);

        // 新增入住信息
        CheckIn checkIn = new CheckIn();
        checkIn.setBedNumber(newElder.getBedNumber());
        checkIn.setElderId(newElder.getId());
        checkIn.setElderName(newElder.getName());
        checkIn.setStartDate(checkInApplyDto.getCheckInConfigDto().getStartDate());
        checkIn.setEndDate(checkInApplyDto.getCheckInConfigDto().getEndDate());
        checkIn.setIdCardNo(newElder.getIdCardNo());
        checkIn.setNursingLevelName(checkInApplyDto.getCheckInConfigDto().getNursingLevelName());
        checkIn.setRemark(JSONUtil.toJsonStr(checkInApplyDto.getElderFamilyDtoList()));
        checkIn.setStatus(0); // 0表示入住
        checkIn.setSortOrder(0);
        checkInMapper.insertCheckIn(checkIn);

        // 新增入住配置信息
        CheckInConfig checkInConfig = new CheckInConfig();
        BeanUtil.copyProperties(checkInApplyDto.getCheckInConfigDto(), checkInConfig);
        checkInConfig.setCheckInId(checkIn.getId());
        checkInConfigMapper.insert(checkInConfig);
    }

    /**
     * 新增或更新老人
     *
     * @param checkInApplyDto
     * @return
     */
    private Elder insertOrUpdate(CheckInApplyDto checkInApplyDto) {
        // 准备老人数据
        Elder elder = new Elder();
        // 属性拷贝
        BeanUtil.copyProperties(checkInApplyDto.getCheckInElderDto(), elder);
        elder.setBedId(checkInApplyDto.getCheckInConfigDto().getBedId());
        elder.setStatus(1);
        Bed bed = bedMapper.selectBedById(elder.getBedId());
        elder.setBedNumber(bed.getBedNumber());

        // 查询判断 老人信息有没有
        LambdaQueryWrapper<Elder> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(Elder::getIdCardNo, elder.getIdCardNo()).eq(Elder::getStatus, 1);
        Elder elderDb = elderMapper.selectOne(lambdaQueryWrapper);
        if (ObjectUtils.isNotEmpty(elderDb)) {
            // 修改
            elderMapper.updateById(elder);
        } else {
            // 新增
            elderMapper.insert(elder);
        }
        return elder;
    }

    /**
     * @param id 入住id
     * @return
     */
    @Override
    public CheckInVo getCheckInById(Integer id) {
        CheckInVo checkInVo = new CheckInVo();

        //查询入住表内的信息
        CheckIn checkIn = checkInMapper.selectById(id);
        LocalDateTime startDate = checkIn.getStartDate();
        LocalDateTime endDate = checkIn.getEndDate();
        String bedNumber = checkIn.getBedNumber();
        Long eldId = checkIn.getElderId();

        //查询老人表内的信息
        Elder elder = elderMapper.selectById(eldId);
        CheckInElderVo checkInElderVo = new CheckInElderVo();
        BeanUtil.copyProperties(elder, checkInElderVo);
        LocalDate birthdayYear = LocalDate.parse(elder.getBirthday());
        LocalDate nowYear = LocalDate.now();
        int age = nowYear.minusYears(birthdayYear.getYear()).getYear() + 1;
        checkInElderVo.setAge(age);
        checkInVo.setCheckInElderVo(checkInElderVo);

        //查询老人家属表内的信息
        List<ElderFamilyVo> elderFamilyVoList = new ArrayList<>();
        elderFamilyVoList = JSONUtil.toList(checkIn.getRemark(), ElderFamilyVo.class);
        checkInVo.setElderFamilyVoList(elderFamilyVoList);

        //查询入住配置表内的信息
        CheckInConfig checkInConfig = checkInConfigMapper.selectByCheckInId(checkIn.getId());
        CheckInConfigVo checkInConfigVo = new CheckInConfigVo();
        BeanUtil.copyProperties(checkInConfig, checkInConfigVo);
        checkInConfigVo.setStartDate(startDate);
        checkInConfigVo.setEndDate(endDate);
        checkInConfigVo.setBedNumber(bedNumber);
        checkInVo.setCheckInConfigVo(checkInConfigVo);

        //查询签约办理表内的信息
        CheckInContractVo checkInContractVo = new CheckInContractVo();
        Contract contract = contractMapper.selectByElderId(elder.getId());
        BeanUtil.copyProperties(contract, checkInContractVo);
        checkInVo.setContract(checkInContractVo);
        return checkInVo;
    }
}
